<template>
  <div class="document-manager">
    <!-- 顶部标题栏 -->
    <div class="header">
      <div class="breadcrumb-container">
        <div class="breadcrumb-scroll">
          <div class="breadcrumb" v-if="activeDocument || currentNode">
            <template v-if="currentPath.length <= 3">
              <span v-for="(item, index) in currentPath" :key="item.id">
                <span @click="navigateToPath(item)" class="breadcrumb-item">
                  <el-icon class="breadcrumb-icon">
                    <Folder
                      v-if="
                        item.type === 'folder' && index < currentPath.length - 1
                      "
                    />
                    <FolderOpened v-else-if="item.type === 'folder'" />
                    <Document v-else />
                  </el-icon>
                  {{ item.label }}
                </span>
                <span v-if="index < currentPath.length - 1" class="separator">
                  <el-icon><ArrowRight /></el-icon>
                </span>
              </span>
            </template>
            <template v-else>
              <span
                @click="navigateToPath(currentPath[0])"
                class="breadcrumb-item"
              >
                <el-icon class="breadcrumb-icon">
                  <FolderOpened />
                </el-icon>
                {{ currentPath[0].label }}
              </span>
              <span class="separator">
                <el-icon><ArrowRight /></el-icon>
              </span>
              <el-tooltip
                effect="dark"
                :content="getMiddlePath()"
                placement="top"
              >
                <span class="breadcrumb-ellipsis">
                  <el-icon><MoreFilled /></el-icon>
                </span>
              </el-tooltip>
              <span class="separator">
                <el-icon><ArrowRight /></el-icon>
              </span>
              <span
                @click="navigateToPath(currentPath[currentPath.length - 1])"
                class="breadcrumb-item"
              >
                <el-icon class="breadcrumb-icon">
                  <Document
                    v-if="
                      currentPath[currentPath.length - 1].type === 'document'
                    "
                  />
                  <FolderOpened v-else />
                </el-icon>
                {{ currentPath[currentPath.length - 1].label }}
              </span>
            </template>
          </div>
        </div>
      </div>
      <div class="actions">
        <el-input
          v-model="searchQuery"
          placeholder="搜索文档或文件夹..."
          clearable
          style="width: 240px; margin-right: 12px"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>

        <div class="action-buttons">
          <!-- 新建操作下拉菜单 -->
          <el-dropdown trigger="click">
            <el-button type="primary" icon="Plus" circle />
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item @click="addDocument(null)">
                  <el-icon><DocumentAdd /></el-icon>
                  <span>新建文档</span>
                </el-dropdown-item>
                <el-dropdown-item @click="addFolder(null)">
                  <el-icon><FolderAdd /></el-icon>
                  <span>新建文件夹</span>
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>

          <!-- 编辑/保存按钮 -->
          <el-tooltip
            :content="activeDocument?.editing ? '保存文档' : '编辑文档'"
            placement="bottom"
          >
            <el-button
              v-if="!activeDocument?.editing"
              type="primary"
              icon="Edit"
              circle
              @click="toggleEditMode"
              :disabled="!activeDocument"
            />
            <el-button
              v-else
              type="success"
              icon="Check"
              circle
              @click="saveDocument"
            />
          </el-tooltip>

          <!-- 文档状态操作按钮 -->
          <template v-if="activeDocument && !activeDocument.editing">
            <!-- 草稿状态：显示发布和提交审核按钮 -->
            <template v-if="activeDocument.status === '草稿'">
              <el-tooltip content="发布文档" placement="bottom">
                <el-button 
                  type="success"
                  icon="CircleCheck"
                  circle 
                  @click="publishDocument"
                />
              </el-tooltip>
              <el-tooltip content="提交审核" placement="bottom">
                <el-button 
                  type="warning"
                  icon="Finished"
                  circle 
                  @click="submitForReview"
                />
              </el-tooltip>
            </template>
            
            <!-- 审核中状态：显示撤销审核按钮 -->
            <template v-else-if="activeDocument.status === '审核中'">
              <el-tooltip content="撤销审核" placement="bottom">
                <el-button 
                  type="warning"
                  icon="RefreshLeft"
                  circle 
                  @click="withdrawReview"
                />
              </el-tooltip>
            </template>
            
            <!-- 已发布状态：显示下架按钮 -->
            <template v-else-if="activeDocument.status === '已发布'">
              <el-tooltip content="下架文档" placement="bottom">
                <el-button 
                  type="danger"
                  icon="Remove"
                  circle 
                  @click="unpublishDocument"
                />
              </el-tooltip>
            </template>
          </template>

          <el-tooltip content="分享" placement="bottom">
            <el-button
              type="primary"
              icon="Share"
              circle
              @click="shareDocument"
              :disabled="!activeDocument || activeDocument.editing"
            />
          </el-tooltip>

          <template v-if="!showMoreActions">
            <el-tooltip content="收藏" placement="bottom" v-if="activeDocument">
              <el-button
                type="primary"
                icon="Star"
                circle
                @click="collectDocument"
                :disabled="!activeDocument || activeDocument.editing"
              />
            </el-tooltip>
            <el-tooltip content="删除" placement="bottom">
              <el-button
                type="danger"
                icon="Delete"
                circle
                @click="deleteDocument"
                :disabled="
                  (!activeDocument && !currentNode) || activeDocument?.editing
                "
              />
            </el-tooltip>
          </template>

          <el-dropdown trigger="click" v-if="showMoreActions">
            <el-button
              type="primary"
              icon="MoreFilled"
              circle
              :disabled="activeDocument?.editing"
            />
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item
                  @click="collectDocument"
                  v-if="activeDocument"
                  :disabled="activeDocument.editing"
                >
                  <el-icon><Star /></el-icon>
                  <span>收藏</span>
                </el-dropdown-item>
                <el-dropdown-item
                  @click="deleteDocument"
                  :disabled="activeDocument?.editing"
                >
                  <el-icon><Delete /></el-icon>
                  <span>删除</span>
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </div>
    </div>

    <!-- 主内容区 -->
    <div class="main-content">
      <!-- 左侧树形目录 -->
      <div class="directory-tree-container">
        <div class="directory-tree">
          <el-tree
            ref="treeRef"
            :data="treeData"
            :props="treeProps"
            :filter-node-method="filterNode"
            node-key="id"
            highlight-current
            :expand-on-click-node="false"
            :default-expanded-keys="expandedKeys"
            draggable
            @node-drop="handleNodeDrop"
            @node-click="handleNodeClick"
            @node-contextmenu="handleContextMenu"
          >
            <template #default="{ node, data }">
              <div class="tree-node">
                <el-icon v-if="data.type === 'folder'" class="folder-icon">
                  <FolderOpened v-if="node.expanded" />
                  <Folder v-else />
                </el-icon>
                <el-icon v-else class="document-icon">
                  <Document />
                </el-icon>

                <span v-if="!data.editing" class="node-label">{{
                  node.label
                }}</span>

                <el-input
                  v-else
                  ref="renameInput"
                  v-model="data.label"
                  size="small"
                  @blur="finishRename(data)"
                  @keyup.enter="finishRename(data)"
                />

                <div v-if="data.type === 'document'" class="node-tags">
                  <el-tag
                    :type="getStatusType(data.status)"
                    size="small"
                    effect="plain"
                  >
                    {{ data.status }}
                  </el-tag>
                </div>
              </div>
            </template>
          </el-tree>
        </div>
      </div>

      <!-- 右侧文档预览区 -->
      <div class="preview-panel">
        <div v-if="activeDocument" class="preview-content">
          <div class="preview-header">
            <h2 v-if="!activeDocument.editing">{{ activeDocument.label }}</h2>
            <el-input
              v-else
              v-model="activeDocument.label"
              size="large"
              style="font-size: 24px; font-weight: bold; margin-bottom: 10px"
              @blur="finishRename(activeDocument)"
              @keyup.enter="finishRename(activeDocument)"
            />

            <div class="preview-meta">
              <span>{{ activeDocument.createDate }}</span>
              <el-rate
                v-model="activeDocument.rating"
                :disabled="activeDocument.editing"
              />
            </div>
          </div>

          <div>
            <YEditor
              v-model="activeDocument.content"
              :initialMode="activeDocument.editing ? 'edit' : 'preview'"
              class="custom-editor"
            />
          </div>
          <br />
          <div class="preview-keywords">
            <y-tag v-model="activeDocument.keywords" />
          </div>
        </div>

        <div v-else class="empty-preview">
          <el-icon class="empty-icon"><Document /></el-icon>
          <h3>选择文档进行预览</h3>
          <p>从左侧树形目录中选择文档查看详细内容</p>
          <el-button
            type="primary"
            icon="DocumentAdd"
            @click="addDocument(null)"
            >创建新文档</el-button
          >
        </div>
      </div>
    </div>

    <!-- 节点操作菜单 -->
    <div
      v-if="contextMenuVisible"
      class="context-menu"
      :style="{ top: contextMenuY + 'px', left: contextMenuX + 'px' }"
      @mouseleave="contextMenuVisible = false"
    >
      <div v-if="currentNode.type === 'folder'" class="menu-section">
        <div class="menu-header">文件夹操作</div>
        <div class="menu-item" @click="addFolder('sibling')">
          <el-icon><FolderAdd /></el-icon>
          <span>添加同级文件夹</span>
        </div>
        <div class="menu-item" @click="addFolder('child')">
          <el-icon><FolderAdd /></el-icon>
          <span>添加子文件夹</span>
        </div>
        <div class="menu-item" @click="addDocument('child')">
          <el-icon><DocumentAdd /></el-icon>
          <span>添加子文档</span>
        </div>
        <div class="menu-divider"></div>
        <div class="menu-item" @click="startRename">
          <el-icon><Edit /></el-icon>
          <span>重命名</span>
        </div>
        <div class="menu-item" @click="deleteFolder">
          <el-icon><Delete /></el-icon>
          <span>删除文件夹</span>
        </div>
      </div>

      <div v-else class="menu-section">
        <div class="menu-header">文档操作</div>
        <div class="menu-item" @click="addDocument('sibling')">
          <el-icon><DocumentAdd /></el-icon>
          <span>添加同级文档</span>
        </div>
        <div class="menu-item" @click="startRename">
          <el-icon><Edit /></el-icon>
          <span>重命名</span>
        </div>
        <div class="menu-item" @click="deleteDocument">
          <el-icon><Delete /></el-icon>
          <span>删除文档</span>
        </div>
        <div class="menu-divider"></div>
        <!-- 新增：文档状态操作菜单项 -->
        <template v-if="currentNode.status === '草稿'">
          <div class="menu-item" @click="publishDocument">
            <el-icon><CircleCheck /></el-icon>
            <span>发布文档</span>
          </div>
          <div class="menu-item" @click="submitForReview">
            <el-icon><Finished /></el-icon>
            <span>提交审核</span>
          </div>
        </template>
        <template v-else-if="currentNode.status === '审核中'">
          <div class="menu-item" @click="withdrawReview">
            <el-icon><RefreshLeft /></el-icon>
            <span>撤销审核</span>
          </div>
        </template>
        <template v-else-if="currentNode.status === '已发布'">
          <div class="menu-item" @click="unpublishDocument">
            <el-icon><Remove /></el-icon>
            <span>下架文档</span>
          </div>
        </template>
        <div class="menu-divider"></div>
        <div class="menu-item" @click="toggleEditMode">
          <el-icon><EditPen /></el-icon>
          <span>{{ activeDocument?.editing ? "保存文档" : "编辑文档" }}</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
const { proxy } = getCurrentInstance();

// 树形目录数据
const treeData = ref([
  {
    id: "folder-1",
    label: "产品文档",
    type: "folder",
    children: [
      {
        id: 1,
        label: "浏览创建",
        type: "document",
        status: "草稿",
        createDate: "07月21日创建",
        rating: 4,
        keywords: ["UI设计", "产品文档"],
        content:
          "<h1>产品需求文档</h1><p>这是关于<b>浏览创建</b>功能的产品需求文档。</p><p>主要功能点：</p><ul><li>支持多标签浏览</li><li>拖拽创建新标签</li><li>自定义浏览布局</li></ul>",
      },
      {
        id: 2,
        label: "项目需求文档",
        type: "document",
        status: "已发布",
        createDate: "07月18日创建",
        rating: 5,
        keywords: ["需求", "开发"],
        content:
          "<h2>项目需求文档</h2><p>本文档详细描述了系统的主要功能和需求。</p><p>功能模块：</p><ol><li>用户管理</li><li>权限控制</li><li>数据统计</li></ol>",
      },
    ],
  },
  {
    id: "folder-2",
    label: "用户手册",
    type: "folder",
    children: [
      {
        id: 3,
        label: "用户指南",
        type: "document",
        status: "审核中",
        createDate: "07月15日创建",
        rating: 3,
        keywords: ["用户指南", "帮助文档"],
        content:
          "<h1>用户手册</h1><p>欢迎使用我们的产品，本手册将帮助您快速上手。</p><p>主要内容：</p><ul><li>安装指南</li><li>功能使用说明</li><li>常见问题解答</li></ul>",
      },
      {
        id: 4,
        label: "API文档",
        type: "document",
        status: "已发布",
        createDate: "07月10日创建",
        rating: 4,
        keywords: ["API", "开发文档"],
        content:
          "<h1>API接口文档</h1><p>本文档提供了系统所有API接口的详细说明。</p><table><tr><th>接口名称</th><th>方法</th><th>路径</th></tr><tr><td>用户列表</td><td>GET</td><td>/api/users</td></tr><tr><td>创建用户</td><td>POST</td><td>/api/users</td></tr></table>",
      },
    ],
  },
  {
    id: 5,
    label: "个人笔记",
    type: "document",
    status: "草稿",
    createDate: "07月22日创建",
    rating: 3,
    keywords: ["个人", "笔记"],
    content:
      "<h2>个人学习笔记</h2><p>今日学习要点：</p><ul><li>Vue3 Composition API</li><li>Element Plus组件使用</li><li>富文本编辑器集成</li></ul>",
  },
]);

// 树形配置
const treeProps = ref({
  label: "label",
  children: "children",
});

// 当前选中的文档
const activeDocument = ref(null);
// 当前操作的节点
const currentNode = ref(null);
// 搜索查询
const searchQuery = ref("");
// 树形组件引用
const treeRef = ref(null);
// 重命名输入框引用
const renameInput = ref(null);

// 默认展开的节点
const expandedKeys = ref(["folder-1", "folder-2"]);

// 上下文菜单控制
const contextMenuVisible = ref(false);
const contextMenuX = ref(0);
const contextMenuY = ref(0);

// 计算当前路径
const currentPath = computed(() => {
  const path = [];
  if (!currentNode.value) return path;

  const findPath = (nodes, targetId) => {
    for (const node of nodes) {
      if (node.id === targetId) {
        path.unshift(node);
        return true;
      }
      if (node.children) {
        if (findPath(node.children, targetId)) {
          path.unshift(node);
          return true;
        }
      }
    }
    return false;
  };

  findPath(treeData.value, currentNode.value.id);
  return path;
});

// 获取中间路径的完整内容
const getMiddlePath = () => {
  if (currentPath.value.length <= 3) return "";
  return currentPath.value
    .slice(1, -1)
    .map((item) => item.label)
    .join("  / ");
};

// 是否显示更多操作下拉菜单
const showMoreActions = computed(() => {
  // 计算当前可见的操作按钮数量
  let visibleActionCount = 4; // 固定显示的操作按钮: 新建文件夹、新建文档、编辑、分享

  // 根据条件增加可见按钮
  if (activeDocument.value) {
    visibleActionCount += 2; // 收藏、删除
  } else if (currentNode.value) {
    visibleActionCount += 1; // 删除
  }

  // 当可见操作按钮超过5个时，显示更多下拉菜单
  return visibleActionCount > 5;
});

// 根据状态获取标签类型
const getStatusType = (status) => {
  switch (status) {
    case "草稿":
      return "warning";
    case "已发布":
      return "success";
    case "审核中":
      return "info";
    default:
      return "";
  }
};

// 处理树节点点击
const handleNodeClick = (data) => {
  currentNode.value = data;
  if (data.type === "document") {
    activeDocument.value = data;
  }
};

// 导航到路径
const navigateToPath = (item) => {
  treeRef.value.setCurrentKey(item.id);
  if (item.type === "document") {
    activeDocument.value = item;
  }
};

// 过滤树节点
const filterNode = (value, data) => {
  if (!value) return true;
  return data.label.toLowerCase().includes(value.toLowerCase());
};

// 监听搜索查询变化
watch(searchQuery, (val) => {
  treeRef.value.filter(val);
});

// 处理节点拖放
const handleNodeDrop = (draggingNode, dropNode, dropType) => {
  console.log(
    `节点 ${draggingNode.data.label}  被移动到 ${dropType} ${dropNode.data.label}`
  );
};

// 处理右键菜单
const handleContextMenu = (event, data, node, element) => {
  event.preventDefault();
  currentNode.value = data;
  contextMenuX.value = event.clientX;
  contextMenuY.value = event.clientY;
  contextMenuVisible.value = true;
  treeRef.value.setCurrentKey(data.id);
};

// 添加文件夹
const addFolder = (position) => {
  const newFolder = {
    id: `folder-${Date.now()}`,
    label: "新建文件夹",
    type: "folder",
    children: [],
    editing: true,
  };

  if (!position) {
    // 添加到根节点
    treeData.value.push(newFolder);
    expandedKeys.value.push(newFolder.id);
    treeRef.value.setCurrentKey(newFolder.id);
    return;
  }

  if (!currentNode.value) return;

  if (currentNode.value.type === "folder") {
    if (position === "sibling") {
      // 添加到同级
      const parent = treeRef.value.getNode(currentNode.value).parent;
      if (parent.level === 0) {
        // 根节点
        treeData.value.splice(
          treeData.value.indexOf(currentNode.value) + 1,
          0,
          newFolder
        );
      } else {
        parent.data.children.splice(
          parent.data.children.indexOf(currentNode.value) + 1,
          0,
          newFolder
        );
      }
    } else if (position === "child") {
      // 添加到子节点
      if (!currentNode.value.children) currentNode.value.children = [];
      currentNode.value.children.push(newFolder);
      treeRef.value.setCurrentKey(newFolder.id);
    }
    expandedKeys.value.push(newFolder.id);
  }

  // 设置新文件夹为编辑状态
  nextTick(() => {
    newFolder.editing = true;
    treeRef.value.setCurrentKey(newFolder.id);
    setTimeout(() => {
      if (renameInput.value) {
        renameInput.value.focus();
      }
    }, 50);
  });
};

// 添加文档
const addDocument = (position) => {
  const newDoc = {
    id: Date.now(),
    label: "未命名文档",
    type: "document",
    status: "草稿",
    createDate: "刚刚创建",
    rating: 0,
    keywords: [],
    content: "<p>请输入文档内容...</p>",
    editing: true,
  };

  if (!position && !currentNode.value) {
    // 添加到根节点
    treeData.value.push(newDoc);
    treeRef.value.setCurrentKey(newDoc.id);
    activeDocument.value = newDoc;
    return;
  }

  if (currentNode.value) {
    if (position === "sibling") {
      // 添加到同级
      const parent = treeRef.value.getNode(currentNode.value).parent;
      if (parent.level === 0) {
        // 根节点
        treeData.value.splice(
          treeData.value.indexOf(currentNode.value) + 1,
          0,
          newDoc
        );
      } else {
        parent.data.children.splice(
          parent.data.children.indexOf(currentNode.value) + 1,
          0,
          newDoc
        );
      }
    } else if (position === "child" && currentNode.value.type === "folder") {
      // 添加到子节点
      if (!currentNode.value.children) currentNode.value.children = [];
      currentNode.value.children.push(newDoc);
    } else {
      // 添加到当前文件夹
      if (currentNode.value.type === "folder") {
        if (!currentNode.value.children) currentNode.value.children = [];
        currentNode.value.children.push(newDoc);
      } else {
        // 文档节点，添加到同级
        const parent = treeRef.value.getNode(currentNode.value).parent;
        if (parent.level === 0) {
          treeData.value.push(newDoc);
        } else {
          parent.data.children.push(newDoc);
        }
      }
    }
  }

  // 选中新文档
  treeRef.value.setCurrentKey(newDoc.id);
  activeDocument.value = newDoc;
};

// 开始重命名
const startRename = () => {
  if (currentNode.value) {
    currentNode.value.editing = true;
    contextMenuVisible.value = false;

    nextTick(() => {
      if (renameInput.value) {
        renameInput.value.focus();
      }
    });
  }
};

// 新增：发布文档
const publishDocument = () => {
  if (activeDocument.value) {
    activeDocument.value.status = '已发布';
    proxy.$modal.msgSuccess(`文档 "${activeDocument.value.label}" 已发布`);
  } else if (currentNode.value) {
    currentNode.value.status = '已发布';
    proxy.$modal.msgSuccess(`文档 "${currentNode.value.label}" 已发布`);
  }
  contextMenuVisible.value = false;
};

// 新增：提交审核
const submitForReview = () => {
  if (activeDocument.value) {
    activeDocument.value.status = '审核中';
    proxy.$modal.msgSuccess(`文档 "${activeDocument.value.label}" 已提交审核`);
  } else if (currentNode.value) {
    currentNode.value.status = '审核中';
    proxy.$modal.msgSuccess(`文档 "${currentNode.value.label}" 已提交审核`);
  }
  contextMenuVisible.value = false;
};

// 新增：撤销审核
const withdrawReview = () => {
  if (activeDocument.value) {
    activeDocument.value.status = '草稿';
    proxy.$modal.msgSuccess(`文档 "${activeDocument.value.label}" 已撤销审核`);
  } else if (currentNode.value) {
    currentNode.value.status = '草稿';
    proxy.$modal.msgSuccess(`文档 "${currentNode.value.label}" 已撤销审核`);
  }
  contextMenuVisible.value = false;
};

// 新增：下架文档
const unpublishDocument = () => {
  if (activeDocument.value) {
    activeDocument.value.status = '草稿';
    proxy.$modal.msgSuccess(`文档 "${activeDocument.value.label}" 已下架`);
  } else if (currentNode.value) {
    currentNode.value.status = '草稿';
    proxy.$modal.msgSuccess(`文档 "${currentNode.value.label}" 已下架`);
  }
  contextMenuVisible.value = false;
};

// 完成重命名
const finishRename = (node) => {
  node.editing = false;
};

// 删除文件夹
const deleteFolder = () => {
  if (!currentNode.value || currentNode.value.type !== "folder") return;

  const confirm = window.confirm(
    `确定要删除文件夹 "${currentNode.value.label}"  及其所有内容吗？`
  );
  if (!confirm) return;

  // 递归删除节点
  const deleteNode = (nodes, id) => {
    for (let i = 0; i < nodes.length; i++) {
      if (nodes[i].id === id) {
        nodes.splice(i, 1);
        return true;
      }
      if (nodes[i].children) {
        if (deleteNode(nodes[i].children, id)) {
          return true;
        }
      }
    }
    return false;
  };

  deleteNode(treeData.value, currentNode.value.id);

  // 如果删除的是当前选中的文档所在的文件夹
  if (
    activeDocument.value &&
    findParentFolder(activeDocument.value.id)?.id === currentNode.value.id
  ) {
    activeDocument.value = null;
  }

  contextMenuVisible.value = false;
};

// 查找文档的父文件夹
const findParentFolder = (id) => {
  const findParent = (nodes) => {
    for (const node of nodes) {
      if (node.children) {
        for (const child of node.children) {
          if (child.id === id) {
            return node;
          }
        }
        const parent = findParent(node.children);
        if (parent) return parent;
      }
    }
    return null;
  };
  return findParent(treeData.value);
};

// 删除文档
const deleteDocument = () => {
  if (!activeDocument.value && !currentNode.value) return;

  const docToDelete = activeDocument.value || currentNode.value;
  const confirm = window.confirm(
    ` 确定要删除文档 "${docToDelete.label}"  吗？`
  );
  if (!confirm) return;

  // 删除节点
  const deleteNode = (nodes, id) => {
    for (let i = 0; i < nodes.length; i++) {
      if (nodes[i].id === id) {
        nodes.splice(i, 1);
        return true;
      }
      if (nodes[i].children) {
        if (deleteNode(nodes[i].children, id)) {
          return true;
        }
      }
    }
    return false;
  };

  deleteNode(treeData.value, docToDelete.id);

  // 如果删除的是当前选中的文档
  if (activeDocument.value?.id === docToDelete.id) {
    activeDocument.value = null;
  }

  contextMenuVisible.value = false;
};

// 切换编辑模式
const toggleEditMode = () => {
  if (activeDocument.value) {
    activeDocument.value.editing = !activeDocument.value.editing;
  }
  contextMenuVisible.value = false;
};

// 保存文档
const saveDocument = () => {
  if (activeDocument.value) {
    // 这里可以添加保存逻辑（如API调用）
    activeDocument.value.editing = false;
    proxy.$modal.msgSuccess(` 文档 "${activeDocument.value.label}"  已保存`);
  }
};

// 分享文档
const shareDocument = () => {
  if (activeDocument.value) {
    proxy.$modal.msgSuccess(` 文档 "${activeDocument.value.label}"  已分享`);
  }
};

// 收藏文档
const collectDocument = () => {
  if (activeDocument.value) {
    proxy.$modal.msgSuccess(` 文档 "${activeDocument.value.label}"  已收藏`);
  }
};

// 查找树中的第一个文档
const findFirstDocument = (nodes) => {
  for (const node of nodes) {
    if (node.type === "document") {
      return node;
    }
    if (node.children && node.children.length > 0) {
      const doc = findFirstDocument(node.children);
      if (doc) return doc;
    }
  }
  return null;
};

// 模拟数据加载
onMounted(() => {
  // 默认选中第一个文档
  setTimeout(() => {
    const firstDoc = findFirstDocument(treeData.value);
    if (firstDoc) {
      treeRef.value.setCurrentKey(firstDoc.id);
      activeDocument.value = firstDoc;
      currentNode.value = firstDoc;
    }
  }, 100);

  // 点击其他地方关闭上下文菜单
  document.addEventListener("click", () => {
    contextMenuVisible.value = false;
  });
});
</script>

<style scoped>
.document-manager {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f5f7fa;
  font-family: "Helvetica Neue", Arial, sans-serif;
  position: relative;
}

.header {
  background: white;
  padding: 15px 25px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  z-index: 10;
  flex-shrink: 0;
}

.breadcrumb-container {
  flex: 1;
  overflow: hidden;
  margin-right: 20px;
}

.breadcrumb-scroll {
  overflow-x: auto;
  white-space: nowrap;
  scrollbar-width: none; /* Firefox */
  -ms-overflow-style: none; /* IE and Edge */
}

.breadcrumb-scroll::-webkit-scrollbar {
  display: none; /* Chrome, Safari, Opera */
}

.breadcrumb {
  display: inline-flex;
  align-items: center;
  font-size: 16px;
  padding-bottom: 2px; /* 为滚动条留空间 */
}

.breadcrumb-item {
  cursor: pointer;
  color: #606266;
  padding: 4px 6px;
  border-radius: 4px;
  max-width: 200px;
  text-overflow: ellipsis;
  white-space: nowrap;
  overflow: hidden;
  display: inline-flex;
  align-items: center;
}

.breadcrumb-icon {
  margin-right: 6px;
  font-size: 16px;
}

.breadcrumb-item:hover {
  color: #409eff;
  background-color: #f5f7fa;
}

.breadcrumb-ellipsis {
  cursor: pointer;
  color: #606266;
  padding: 4px 6px;
  border-radius: 4px;
  display: inline-flex;
  align-items: center;
}

.breadcrumb-ellipsis:hover {
  color: #409eff;
  background-color: #f5f7fa;
}

.separator {
  margin: 0 8px;
  color: #c0c4cc;
  display: inline-flex;
  align-items: center;
}

.actions {
  display: flex;
  align-items: center;
}

.action-buttons {
  display: flex;
  gap: 8px;
}

.action-buttons .el-button {
  margin-left: 0 !important;
}

.main-content {
  display: flex;
  flex: 1;
  overflow: hidden;
  padding: 20px;
  gap: 20px;
}

.directory-tree-container {
  flex: 0 0 280px;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.directory-tree {
  flex: 1;
  background: white;
  border-radius: 8px;
  padding: 15px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  overflow-y: auto;
  border: 1px solid #ebeef5;
}

.tree-node {
  display: flex;
  align-items: center;
  width: 100%;
  padding: 5px 0;
  position: relative;
}

.tree-node .el-icon {
  margin-right: 8px;
  font-size: 18px;
}

.tree-node .folder-icon {
  color: #e6a23c;
}

.tree-node .document-icon {
  color: #409eff;
}

.node-label {
  flex: 1;
  font-size: 14px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.node-tags {
  margin-left: 10px;
}

.node-actions {
  position: absolute;
  right: 5px;
  opacity: 0;
  transition: opacity 0.2s;
}

.tree-node:hover .node-actions {
  opacity: 1;
}

.preview-panel {
  flex: 1;
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  border: 1px solid #ebeef5;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.preview-content {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.preview-header {
  padding-bottom: 16px;
  border-bottom: 1px solid #ebeef5;
  margin-bottom: 20px;
}

.preview-header h2 {
  margin: 0 0 8px 0;
  color: #303133;
  font-size: 24px;
}

.preview-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: #909399;
  font-size: 14px;
}

.custom-editor {
  min-height: 100%;
}

.preview-keywords {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-bottom: 20px;
}

.empty-preview {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 100%;
  color: #909399;
  text-align: center;
}

.empty-icon {
  font-size: 64px;
  margin-bottom: 20px;
  color: #c0c4cc;
}

.empty-preview h3 {
  margin: 0 0 10px 0;
  font-size: 20px;
  color: #606266;
}

.empty-preview p {
  margin: 0 0 20px 0;
  font-size: 14px;
}

/* 上下文菜单 */
.context-menu {
  position: fixed;
  background: white;
  border-radius: 6px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.15);
  z-index: 1000;
  width: 200px;
  overflow: hidden;
}

.menu-section {
  padding: 8px 0;
}

.menu-header {
  padding: 8px 16px;
  font-size: 12px;
  color: #909399;
  border-bottom: 1px solid #ebeef5;
  margin-bottom: 4px;
}

.menu-item {
  display: flex;
  align-items: center;
  padding: 8px 16px;
  cursor: pointer;
  font-size: 14px;
  transition: background 0.2s;
}

.menu-item:hover {
  background: #f5f7fa;
}

.menu-item .el-icon {
  margin-right: 8px;
  font-size: 16px;
}

.menu-divider {
  height: 1px;
  background: #ebeef5;
  margin: 6px 0;
}

/* 滚动条样式 */
::-webkit-scrollbar {
  width: 8px;
  height: 8px;
}

::-webkit-scrollbar-thumb {
  background-color: #c1c1c1;
  border-radius: 4px;
}

::-webkit-scrollbar-thumb:hover {
  background-color: #a8a8a8;
}

::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 4px;
}

/* 树形目录样式 */
:deep(.el-tree) {
  background-color: transparent;
}

:deep(.el-tree-node__content) {
  height: 36px;
  border-radius: 4px;
}

:deep(.el-tree-node:focus > .el-tree-node__content) {
  background-color: #f0f7ff;
}

:deep(
    .el-tree--highlight-current
      .el-tree-node.is-current
      > .el-tree-node__content
  ) {
  background-color: #f0f7ff;
  font-weight: 500;
}
</style>
